﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.IO;
using ArgusLib;
using ArgusLib.Zip;
using ArgusLib.Controls;
using ArgusPCLib.Bird;

namespace Imagenator.Forms
{
	partial class FeedbackForm : ArgusLib.Controls.BaseForm
	{
		public FeedbackForm()
		{
			InitializeComponent();
		}

		private void bSend_Click(object sender, EventArgs e)
		{
			string subject = this.tbSubject.Text;
			string message = this.tbMessage.Text;
			bool includeScreenshots = this.cbIncludeScreenshots.Checked;

			if (string.IsNullOrEmpty(subject) == true)
			{
				ArgusLib.Controls.MessageBox.Show(Localization.Text.MBMailSubjectText, Localization.Text.MBMailSubjectCaption);
				return;
			}
			if (string.IsNullOrEmpty(message) == true)
			{
				ArgusLib.Controls.MessageBox.Show(Localization.Text.MBMailMessageText, Localization.Text.MBMailMessageCaption);
				return;
			}

			ServerResponses serverResponse = ServerResponses.FailureResponse;

			ProgressBox.ShowMarquee(Localization.Text.MBSending, new Action<ProgressBox.SetProgressTextHandler>((textHandler) =>
				{
					using (TempDirectory tempDir = TempDirectory.Create())
					{
						subject = "Feedback Imagenator v" + ArgusLib.Environment.GetAssemblyVersion().ToString() + ": " + subject;

						byte[] attachment = null;
						if (includeScreenshots == true)
						{
							FileInfo zipFileInfo = tempDir.DirectoryInfo.CombineFile("Screenshots.zip");
							using (ZipFile zipFile = new ZipFile(zipFileInfo.FullName))
							{
								zipFile.CompressionLevel = ArgusLib.Zlib.CompressionLevel.BestCompression;
								foreach (Form form in Application.OpenForms)
								{
									using (Bitmap screenshot = new Bitmap(form.Width, form.Height))
									{
										form.Invoke(new System.Action(() => { form.DrawToBitmap(screenshot, new Rectangle(0, 0, form.Width, form.Height)); }));
										FileInfo file = tempDir.GetTempFile(". " + form.Text + ".png");
										screenshot.Save(file.FullName, System.Drawing.Imaging.ImageFormat.Png);
										zipFile.AddFile(file.FullName, "");
									}
								}
								zipFile.Save();
							}
							attachment = File.ReadAllBytes(zipFileInfo.FullName);
						}

						serverResponse = MailServer.Send(ServerInfo.MailServerAdress, subject, message, message, attachment, "Screenshots.zip").Result;
					}
				}));
			if (serverResponse == ServerResponses.SuccessResponse)
			{
				this.Close();
			}
			else
			{
				ArgusLib.Controls.MessageBox.Show("Message could not be sent.", "Error");
			}
		}
	}
}
